﻿using System;
using System.Collections.Generic;
using common;
using commsvr;
using ProtoBuf;
using Wala.Connection.Objects.Authen;
using Wala.Connection.Helpers;
using System.Threading.Tasks;
using Wala.Connection.Managements;
using Wala.Connection.Exceptions;

namespace Wala.Connection.ComConnections
{
    public class Client
    {
        #region SendToServer
        ///<summary>
        ///Write Data to transfer queue to write to socket
        ///</summary>
        ///<param name="connectionC"></param>
        ///<param name="mess"></param>
        ///<param name="messageType"></param>
        private static void SendToServer(IExtensible mess, int messageType)
        {
            ConnectionManagement conn = ConnectionManagement.Instance;
            try
            {
                byte[] data = Convertor.pb_encode(mess, messageType, conn.MessageId, false);
                conn.write(data, messageType);
            }
            catch (NullReferenceException e)
            {
            }
        }
        #endregion

        //---------------login - logout----------------------------------------------

        #region Log out
        ///<summary>
        ///Log out
        ///</summary>
        public static void Logout(uint userId)
        {
            LogoutMsg logoutMsg = new LogoutMsg();
            logoutMsg.uid = userId;
            SendToServer(logoutMsg, Constants.Constants.CommMessageType.LOGOUT_MSG);
        }
        #endregion

        #region Login
        ///<summary>
        ///Login after authenticate
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        ///<param name="userToken"></param>
        ///<param name="presenceCode"></param>
        ///<param name="statusMsg"></param>
        ///<param name="versionProtocol"></param>
        public static async void Login(uint userId, String userToken, uint presenceCode,
            String statusMsg, String versionProtocol)
        {
            LoginMsg loginMsg = new LoginMsg();
            loginMsg.uid = userId;
            loginMsg.token = userToken;
            loginMsg.presence_code = presenceCode;
            loginMsg.status_msg = statusMsg;
            loginMsg.protocol_version = versionProtocol;

            SendToServer(loginMsg, Constants.Constants.CommMessageType.LOGIN_MSG);

            ConnectionManagement conn = ConnectionManagement.Instance;
            var objectStorageHelper = new StorageHelper<RetAuthen>(StorageType.Local);
            RetAuthen retAuthen = await objectStorageHelper.LoadASync("RetAuthen");            
            conn.IpAddress = (String)retAuthen.Server.Host;
            conn.Port = Convert.ToInt32(retAuthen.Server.Port);
            conn.StartSocket();
        }
        #endregion

        #region Relogin
        ///<summary>
        ///ReConnect after logout
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        ///<param name="userToken"></param>
        ///<param name="presenceCode"></param>
        ///<param name="statusMsg"></param>
        ///<param name="versionProtocol"></param>
        public static async void Relogin(uint userId, String userToken, uint presenceCode,
            String statusMsg, String versionProtocol)
        {
            ReconnectMsg relogin = new ReconnectMsg();
            relogin.uid = userId;
            relogin.token = userToken;
            relogin.presence_code = presenceCode;
            relogin.status_msg = statusMsg;
            relogin.protocol_version = versionProtocol;

            SendToServer(relogin, Constants.Constants.CommMessageType.RECONNECT_MSG);
            ConnectionManagement conn = ConnectionManagement.Instance;
            var objectStorageHelper = new StorageHelper<RetAuthen>(StorageType.Local);
            RetAuthen retAuthen = await objectStorageHelper.LoadASync("RetAuthen");  
            conn.IpAddress = (String)retAuthen.Server.Host;
            conn.Port = Convert.ToInt32(retAuthen.Server.Port);
            conn.StartSocket();
        }
        #endregion

        #region authenticate
        #region authenticate
        ///<summary>
        ///Authenticate in first login with phone number and password
        ///</summary>
        ///<param name="phoneNumber"></param>
        ///<param name="password"></param>
        public async static Task<bool> AuthenticateAsync(String phoneNumber, String password)
        {
            try
            {
                RetAuthen retAuthen = await LoginManager.LoginServer(phoneNumber, password);

                //ConnectionManagement conn = ConnectionManagement.Instance;
                //conn.IpAddress = retAuthen.Server.Host;
                //conn.Port = retAuthen.Server.Port;
                //conn.Start();

                //String status = "";

                //Client.Login(Convert.ToUInt32(retAuthen.User.Id), retAuthen.User.Token,
                //               Constants.Constants.PresenceCode.PRESENCE_AVAILABLE, status, Constants.Constants.VERSION_PROTOCOL);
                return true;
            }
            catch (AuthenticalFailException ex)
            {
                return false;
            }
        }
        #endregion
        #endregion

        //---------------------------------------------------------------------------


        //----------------group------------------------------------------------------

        #region Load conversation group
        ///<summary>
        ///Load conversation group 
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        public static void LoadConversationGroup(uint userId)
        {
            LoadConversationGroupMsg loadConversationGroupMsg = new LoadConversationGroupMsg();
            loadConversationGroupMsg.uid = userId;

            SendToServer(loadConversationGroupMsg, Constants.Constants.CommMessageType.LOAD_CONVERSATION_GROUP_MSG);
        }
        #endregion

        #region add conversation group
        ///<summary>
        ///add conversation group
        ///</summary>
        public static void AddConverstationGroup(uint userId, ulong groupId, String groupName)
        {
            AddConversationGroupMsg addConversationGroupMsg = new AddConversationGroupMsg();
            addConversationGroupMsg.group_id = groupId;
            addConversationGroupMsg.group_name = groupName;
            addConversationGroupMsg.uid = userId;

            SendToServer(addConversationGroupMsg, Constants.Constants.CommMessageType.ADD_CONVERSATION_GROUP_MSG);
        }
        #endregion

        #region send group chat
        ///<summary>
        ///send group chat
        ///</summary>
        public static void SendChatGroup(uint userId, String displayName,
           ulong groupId, uint messageType, String msg, uint timeStamp)
        {

            GroupChatMsg groupChatMsg = new GroupChatMsg();
            groupChatMsg.uid_from = userId;
            groupChatMsg.uname_from = displayName;
            groupChatMsg.gid = groupId;
            groupChatMsg.msg_type = messageType;
            groupChatMsg.msg = msg;
            groupChatMsg.time_stamp = timeStamp;

            SendToServer(groupChatMsg, Constants.Constants.CommMessageType.SEND_GROUP_CHAT_MSG);
        }
        #endregion

        #region Send a text group chat message
        ///<summary>
        ///Send a text group chat message
        ///</summary>

        public static void SendSimpleGroupMessageChat(String messageContent, ulong groupId)
        {
            //Thread thread = new Thread(new ParameterizedThreadStart(SendSimpleGroupMessageChatMethod));
            //thread.Start(new TextMessageData(messageContent, 0, groupId));
        }
        private static void SendSimpleGroupMessageChatMethod(object data)
        {
            //TextMessageData textMessageData = (TextMessageData)data;
            //string messageContent = textMessageData.Content;
            //uint friendId = textMessageData.FriendId;
            //ulong groupId = textMessageData.GroupId;

            //uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
            //SMS newSms = new SMS(0, messageContent, true, true, Constants.Constants.MessageStatus.SENDING, timeStamp, friendId, groupId, Constants.Constants.MessageType.MESSAGE_SIMPLE);

            //ConnectionManagement conn = ConnectionManagement.Instance;
            //conn.ChatDictionary.Add(conn.MessageId, newSms);
            //newSms.CoreMessageId = conn.MessageId;

            //uint uid = (uint)Wala.Connection.Properties.Settings.Default.RetAuthenServer.User.Id;
            //String displayName = Properties.Settings.Default.DisplayName;


            //SendChatGroup(uid, displayName, groupId, Constants.Constants.MessageType.MESSAGE_SIMPLE, messageContent, timeStamp);
        }
        #endregion

        #region Send a gif image group chat message
        ///<summary>
        ///Send a gif image group chat message
        ///</summary>
        public static void SendGifGroupMessageChat(String messageContent, ulong groupId)
        {
            //Thread thread = new Thread(new ParameterizedThreadStart(SendGifGroupMessageChatMethod));
            //thread.Start(new TextMessageData(messageContent, 0, groupId));
        }

        private static void SendGifGroupMessageChatMethod(object data)
        {
            //TextMessageData textMessageData = (TextMessageData)data;
            //String messageContent = textMessageData.Content;
            //uint friendId = textMessageData.FriendId;
            //ulong groupId = textMessageData.GroupId;

            //uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
            //SMS newSms = new SMS(0, messageContent, true, true, Constants.Constants.MessageStatus.SENDING,
            //    timeStamp, friendId, groupId, Constants.Constants.MessageType.MESSAGE_HTML_GIF);

            //ConnectionManagement conn = ConnectionManagement.Instance;
            //conn.ChatDictionary.Add(conn.MessageId, newSms);
            //newSms.CoreMessageId = conn.MessageId;

            //uint uid = (uint)Wala.Connection.Properties.Settings.Default.RetAuthenServer.User.Id;
            //String displayName = Properties.Settings.Default.DisplayName;

            //SendChatGroup(uid, displayName, groupId, Constants.Constants.MessageType.MESSAGE_HTML_GIF, messageContent, timeStamp);
        }
        #endregion

        #region Send a Image group chat message
        ///<summary>
        ///Send a Image group chat message
        ///</summary>

        public static void SendImageGroupMessageChat(String url, ulong groupId)
        {
            //Thread thread = new Thread(new ParameterizedThreadStart(SendImageMessageChatMethod));
            //thread.Start(new TextMessageData(url, 0, groupId));
        }

        private static void SendImageGroupMessageChatMethod(object data)
        {
            //TextMessageData textMessageData = (TextMessageData)data;
            //String url = textMessageData.Content;
            //uint friendId = textMessageData.FriendId;
            //ulong groupId = textMessageData.GroupId;

            //uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
            //SMS newSms = new SMS(0, url, true, true, Constants.Constants.MessageStatus.SENDING,
            //    timeStamp, friendId, groupId, Constants.Constants.MessageType.MESSAGE_IMAGE);

            //ConnectionManagement conn = ConnectionManagement.Instance;
            //conn.ChatDictionary.Add(conn.MessageId, newSms);
            //newSms.CoreMessageId = conn.MessageId;

            //uint uid = (uint)Wala.Connection.Properties.Settings.Default.RetAuthenServer.User.Id;
            //String displayName = Properties.Settings.Default.DisplayName;

            //SendChatGroup(uid, displayName, groupId, Constants.Constants.MessageType.MESSAGE_IMAGE, url, timeStamp);
        }

        #endregion

        #region get group member
        ///<summary>
        ///get group member
        ///</summary>
        public static void GetGroupMembers(uint userId, ulong groupId)
        {
            GetGroupMemberList getGroupMemberList = new GetGroupMemberList();
            getGroupMemberList.gid = groupId;
            getGroupMemberList.uid = userId;
            SendToServer(getGroupMemberList, Constants.Constants.CommMessageType.GET_GROUP_MEMBER_LIST_MSG);
        }
        #endregion

        #region kick user out of group
        ///<summary>
        ///kick user out of group
        ///</summary>
        public static void KickUserOutOfGroup(uint userId, ulong groupId, uint friendId)
        {
            RemoveGroupMember rgm = new RemoveGroupMember();
            rgm.gid = groupId;
            rgm.uid = userId;
            rgm.removed_uid = friendId;
            SendToServer(rgm, Constants.Constants.CommMessageType.REMOVE_GROUP_MEMBER_MSG);
        }
        #endregion

        #region add user to group chat
        ///<summary>
        ///add user to group chat
        ///</summary>
        public static void InviteIntoGroupChat(uint userId, List<uint> listFriendId, ulong groupChatId)
        {
            //InviteToGroupMsg inviteToGroupMsg = new InviteToGroupMsg();
            //inviteToGroupMsg.gid = groupChatId;
            //inviteToGroupMsg.uid = userId;
            //inviteToGroupMsg.invite_list = listFriendId;
            //SendToServer(inviteToGroupMsg, Constants.Constants.CommMessageType.INVITE_TO_GROUP_MSG);
        }
        #endregion

        #region update conversation group
        ///<summary>
        ///update conversation group
        ///</summary>
        public static void UpdateConversationGroup(uint userId, ulong groupId, String groupName)
        {
            UpdateConversationGroupMsg updateConversationGroup = new UpdateConversationGroupMsg();
            updateConversationGroup.group_id = groupId;
            updateConversationGroup.uid = userId;
            updateConversationGroup.group_name = groupName;
            SendToServer(updateConversationGroup, Constants.Constants.CommMessageType.UPDATE_CONVERSATION_GROUP_MSG);
        }
        #endregion

        #region leave from a  chat group
        ///<summary>
        ///leave from a  chat group
        ///</summary>
        public static void LeaveGroupChat(ulong groupChatId, uint userId)
        {
            LeaveGroupMsg leaveGroupMsg = new LeaveGroupMsg();
            leaveGroupMsg.gid = groupChatId;
            leaveGroupMsg.uid = userId;
            SendToServer(leaveGroupMsg, Constants.Constants.CommMessageType.LEAVE_GROUP_MSG);
        }
        #endregion

        #region delete group conversation
        ///<summary>
        ///delete group conversation
        ///</summary>
        public static void DeleteConversationGroup(uint userId, ulong groupId)
        {
            DeleteConversationGroupMsg deleteConversationGroup = new DeleteConversationGroupMsg();
            deleteConversationGroup.group_id = groupId;
            deleteConversationGroup.uid = userId;

            SendToServer(deleteConversationGroup, Constants.Constants.CommMessageType.DELETE_CONVERSATION_GROUP_MSG);
        }
        #endregion

        //---------------------------------------------------------------------------

        //--------------friend-------------------------------------------------------

        #region Send message Chat
        ///<summary>
        ///Send message Chat
        ///</summary>
        ///<param name="conn">ConnectionManagement instance</param>
        ///<param name="userId">id of current user</param>
        ///<param name="displayName">displayName of current user</param>
        ///<param name="friendId">id of received user</param>
        ///<param name="messageType">type of message</param>
        ///<param name="mess">content of message</param>
        ///<param name="timeStamp">sent time</param>
        public static void SendMsgChat(uint userId, String displayName,
            uint friendId, uint messageType, String mess, uint timeStamp)
        {
            PairChatMsg msg = new PairChatMsg();

            msg.uid_from = userId;
            msg.uid_to = friendId;
            msg.msg = mess;
            msg.uname_from = displayName;
            msg.msg_type = messageType;
            msg.time_stamp = timeStamp;

            SendToServer(msg, Constants.Constants.CommMessageType.SEND_PAIR_CHAT_MSG);
        }
        #endregion

        #region Send a text message
        ///<summary>
        ///send a text message
        ///</summary>
        ///<param name="messageContent">content of message</param>
        ///<param name="friendId">id of received user</param>
        ///<param name="processMessageTimerHandler">timer to process message</param>
        //public static void SendSimpleMessageChat(String messageContent, uint friendId, ProcessMessageTimerHandler processMessageTimerHandler)
        //{
        //    uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
        //    SMS newSms = new SMS(0, messageContent, true, true, Constants.Constants.MessageStatus.SENDING, timeStamp, friendId, timeStamp, 0, Constants.MessageType.MESSAGE_SIMPLE);
        //    IWalaRepository _IwalaRepository = new WalaRepository();
        //    int id = _IwalaRepository.InsertChatMessage(newSms);
        //    int bodyId = _IwalaRepository.InsertNewTextMessageContent(messageContent);
        //    _IwalaRepository.UpdateBodyId(id, bodyId);

        //    newSms.ID = id;
        //    ConnectionManagement conn = ConnectionManagement.Instance;
        //    conn.ChatDictionary.Add(conn.MessageId, newSms);
        //    newSms.CoreMessageId = conn.MessageId;

        //    uint uid = (uint)applicationSetting["uid"];
        //    String displayName = (String)applicationSetting["displayName"];

        //    ChatMessageTimer chatMessageTimer = new ChatMessageTimer(new ChatEventArgs(newSms));
        //    chatMessageTimer.processMessage += processMessageTimerHandler;
        //    chatMessageTimer.start();

        //    SendMsgChat(conn, uid, displayName, friendId, Constants.MessageType.MESSAGE_SIMPLE, messageContent, timeStamp);
        //}

        public static void SendSimpleMessageChat(String messageContent, uint friendId)
        {
            //Thread thread = new Thread(new ParameterizedThreadStart(SendSimpleMessageChatMethod));
            //thread.Start(new TextMessageData(messageContent, friendId));
        }
        private static void SendSimpleMessageChatMethod(object data)
        {
            //TextMessageData textMessageData = (TextMessageData)data;
            //string messageContent = textMessageData.Content;
            //uint friendId = textMessageData.FriendId;

            //uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
            //SMS newSms = new SMS(0, messageContent, true, true, Constants.Constants.MessageStatus.SENDING, timeStamp, friendId, 0, Constants.Constants.MessageType.MESSAGE_SIMPLE);

            //ConnectionManagement conn = ConnectionManagement.Instance;
            //conn.ChatDictionary.Add(conn.MessageId, newSms);
            //newSms.CoreMessageId = conn.MessageId;

            //uint uid = (uint)Wala.Connection.Properties.Settings.Default.RetAuthenServer.User.Id;
            //String displayName = Properties.Settings.Default.DisplayName;            

            //SendMsgChat(uid, displayName, friendId, Constants.Constants.MessageType.MESSAGE_SIMPLE, messageContent, timeStamp);
        }
        #endregion

        #region Send a gif image message
        ///<summary>
        ///send Send a gif image message
        ///</summary>
        ///<param name="messageContent">content of message</param>
        ///<param name="friendId">id of received user</param>
        ///<param name="processMessageTimerHandler">timer to process message</param>
        public static void SendGifMessageChat(String messageContent, uint friendId)
        {
            //Thread thread = new Thread(new ParameterizedThreadStart(SendGifMessageChatMethod));
            //thread.Start(new TextMessageData(messageContent, friendId));
        }

        private static void SendGifMessageChatMethod(object data)
        {
            //TextMessageData textMessageData = (TextMessageData)data;
            //String messageContent = textMessageData.Content;
            //uint friendId = textMessageData.FriendId;

            //uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
            //SMS newSms = new SMS(0, messageContent, true, true, Constants.Constants.MessageStatus.SENDING,
            //    timeStamp, friendId, 0, Constants.Constants.MessageType.MESSAGE_HTML_GIF);

            //ConnectionManagement conn = ConnectionManagement.Instance;
            //conn.ChatDictionary.Add(conn.MessageId, newSms);
            //newSms.CoreMessageId = conn.MessageId;

            //uint uid = (uint)Wala.Connection.Properties.Settings.Default.RetAuthenServer.User.Id;
            //String displayName = Properties.Settings.Default.DisplayName;
            
            //SendMsgChat(uid, displayName, friendId, Constants.Constants.MessageType.MESSAGE_HTML_GIF, messageContent, timeStamp);
        }
        #endregion

        #region Send a Image message
        ///<summary>
        ///send a Image message
        ///</summary>
        ///<param name="imageStream"> content stream of message</param>
        ///<param name="friendId">id of received user</param>
        ///<param name="processMessageTimerHandler">timer to process message</param>

        public static void SendImageMessageChat(String url, uint friendId)
        {
            //Thread thread = new Thread(new ParameterizedThreadStart(SendImageMessageChatMethod));
            //thread.Start(new TextMessageData(url, friendId));
        }

        private static void SendImageMessageChatMethod(object data)
        {
            //TextMessageData textMessageData = (TextMessageData)data;
            //String url = textMessageData.Content;
            //uint friendId = textMessageData.FriendId;

            //uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
            //SMS newSms = new SMS(0, url, true, true, Constants.Constants.MessageStatus.SENDING,
            //    timeStamp, friendId, 0, Constants.Constants.MessageType.MESSAGE_IMAGE);

            //ConnectionManagement conn = ConnectionManagement.Instance;
            //conn.ChatDictionary.Add(conn.MessageId, newSms);
            //newSms.CoreMessageId = conn.MessageId;

            //uint uid = (uint)Wala.Connection.Properties.Settings.Default.RetAuthenServer.User.Id;
            //String displayName = Properties.Settings.Default.DisplayName;

            //SendMsgChat(uid, displayName, friendId, Constants.Constants.MessageType.MESSAGE_IMAGE, url, timeStamp);
        }

        #endregion

        #region Send a voice message
        ///<summary>
        ///send a voice message
        ///</summary>
        ///<param name="voiceStream">content stream of message</param>
        ///<param name="friendId">id of received user</param>
        ///<param name="processMessageTimerHandler">timer to process message</param>
        //public static async void SendVoiceMessageChat(MemoryStream voiceStream, int length, int sampleRate, uint friendId, ProcessMessageTimerHandler processMessageTimerHandler)
        //{
        //    uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
        //    uint uid = (uint)applicationSetting["uid"];
        //    String displayName = (String)applicationSetting["displayName"];

        //    string urlUpload = URLConstant.PHOTO_HOST_UPLOAD + URLConstant.UPLOAD_PHOTO;

        //    Dictionary<string, string> dictionary = new Dictionary<string, string>();
        //    dictionary.Add("uid", uid.ToString());
        //    dictionary.Add("image_name", "lee");
        //    dictionary.Add("filename", "lee");
        //    string result = await ClientHttpUpload.PostAudio(urlUpload, dictionary, voiceStream, sampleRate, "lee");

        //    String url = "";
        //    try
        //    {
        //        JObject jobject = JObject.Parse(result);
        //        url = (String)jobject["url"];
        //    }
        //    catch (System.Exception ex)
        //    {
        //    }

        //    MessageVoice messageVoice = new MessageVoice(url, length);
        //    String json = messageVoice.ToJson();

        //    SMS newSms = new SMS(0, url, true, true, Constants.MessageStatus.SENDING, timeStamp, friendId, timeStamp, 0, Constants.MessageType.MESSAGE_VOICE);
        //    IWalaRepository _IwalaRepository = new WalaRepository();
        //    int id = _IwalaRepository.InsertChatMessage(newSms);
        //    int bodyId = _IwalaRepository.InsertNewVoiceMessageContent(url, length);
        //    _IwalaRepository.UpdateBodyId(id, bodyId);

        //    newSms.ID = id;
        //    ConnectionManagement conn = ConnectionManagement.Instance;
        //    conn.ChatDictionary.Add(conn.MessageId, newSms);
        //    newSms.CoreMessageId = conn.MessageId;

        //    ChatMessageTimer chatMessageTimer = new ChatMessageTimer(new ChatEventArgs(newSms));
        //    chatMessageTimer.processMessage += processMessageTimerHandler;
        //    chatMessageTimer.start();

        //    SendMsgChat(conn, uid, displayName, friendId, Constants.MessageType.MESSAGE_VOICE, json, timeStamp);
        //}
        #endregion

        #region Send a location message
        ///<summary>
        /// Send a location message
        ///</summary>
        ///<param name="detail"></param>
        ///<param name="longitude"></param>
        ///<param name="latitude"></param>
        ///<param name="friendId"></param>
        ///<param name="processMessageTimerHandler">timer to process message</param>
        //public static async void SendLocationMessageChat(String detail, int longitude,int latitude, uint friendId, ProcessMessageTimerHandler processMessageTimerHandler)
        //{
        //    uint timeStamp = Ultility.GetTotalSeconds(DateTime.Now);
        //    uint uid = (uint)applicationSetting["uid"];
        //    String displayName = (String)applicationSetting["displayName"];

        //    MessageLocation messageLocation = new MessageLocation(detail,longitude,latitude);
        //    String json = messageLocation.ToJson();

        //    SMS newSms = new SMS(0, json, true, true, Constants.MessageStatus.SENDING, timeStamp, friendId, timeStamp, 0, Constants.MessageType.MESSAGE_LOCATION);
        //    IWalaRepository _IwalaRepository = new WalaRepository();
        //    int id = _IwalaRepository.InsertChatMessage(newSms);
        //    int bodyId = _IwalaRepository.InsertNewLocationMessageContent(detail, latitude, longitude);
        //    _IwalaRepository.UpdateBodyId(id, bodyId);

        //    newSms.ID = id;
        //    ConnectionManagement conn = ConnectionManagement.Instance;
        //    conn.ChatDictionary.Add(conn.MessageId, newSms);
        //    newSms.CoreMessageId = conn.MessageId;

        //    ChatMessageTimer chatMessageTimer = new ChatMessageTimer(new ChatEventArgs(newSms));
        //    chatMessageTimer.processMessage += processMessageTimerHandler;
        //    chatMessageTimer.start();

        //    SendMsgChat(conn, uid, displayName, friendId, Constants.MessageType.MESSAGE_LOCATION, json, timeStamp);
        //}
        #endregion

        #region Resend message Chat
        ///<summary>
        ///Resend message Chat
        ///</summary>
        ///<param name="conn">ConnectionManagement instance</param>
        ///<param name="userId">id of current user</param>
        ///<param name="displayName">displayName of current user</param>
        ///<param name="sms">sms to resend</param>
        ///<param name="processMessageTimerHandler">timer to process message</param>
        //public static void Resend(ConnectionManagement conn, uint userId, String displayName, SMS sms, ProcessMessageTimerHandler processMessageTimerHandler)
        //{
        //    PairChatMsg msg = new PairChatMsg();
        //    msg.msg_type = sms.Type;
        //    msg.uid_from = userId;
        //    msg.uid_to = sms.FriendId;
        //    msg.msg = sms.Body;
        //    msg.uname_from = displayName;

        //    conn.ChatDictionary.Remove(sms.CoreMessageId);
        //    conn.ChatDictionary.Add(conn.MessageId, sms);
        //    sms.CoreMessageId = conn.MessageId;

        //    ChatMessageTimer chatMessageTimer = new ChatMessageTimer(new ChatEventArgs(sms));
        //    chatMessageTimer.processMessage += processMessageTimerHandler;
        //    chatMessageTimer.start();

        //    SendToServer(conn, msg, Constants.CommMessageType.SEND_PAIR_CHAT_MSG);
        //}
        #endregion

        //----------------------------------------------------------------------------

        //-------------all------------------------------------------------------------
        #region LoadContact
        ///<summary>
        ///Load contact after login success
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        public static void LoadContact(uint userId)
        {
            LoadContactMsg loadContactMsg = new LoadContactMsg();
            loadContactMsg.version = 0;
            loadContactMsg.uid = userId;
            SendToServer(loadContactMsg, Constants.Constants.CommMessageType.LOAD_CONTACT_MSG);
        }
        #endregion

        #region LoadContactBasic
        ///<summary>
        ///Load contact basic after load contact
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        public static void LoadContactBasic(uint userId)
        {
            LoadFriendBasicMsg msg = new LoadFriendBasicMsg();
            msg.uid = userId;
            SendToServer(msg, Constants.Constants.CommMessageType.LOAD_FRIEND_BASIC_MSG);
        }
        #endregion

        #region SetAliasName
        //public static void SetAliasName(ConnectionManagement conn, uint userId, uint friendId, String aliasName)
        //{
        //    SetFriendAliasMsg setFriendAliasMsg = new SetFriendAliasMsg();
        //    setFriendAliasMsg.uid = userId;
        //    setFriendAliasMsg.friend_id = friendId;
        //    setFriendAliasMsg.alias = aliasName;
        //    SendToServer(conn, setFriendAliasMsg, Constants.CommMessageType.SET_FRIEND_ALIAS_MSG);
        //}
        #endregion

        #region SetAliasNameList
        ///<summary>
        ///Set alias name for a list of friend
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        ///<param name="aliasInfos"></param>
        //public static void SetAliasNameList(ConnectionManagement conn, uint userId, List<SetFriendAliasListMsg.AliasInfo> aliasInfos)
        //{

        //    SetFriendAliasListMsg setFriendAliasListMsg = new SetFriendAliasListMsg();
        //    setFriendAliasListMsg.uid = userId;
        //    setFriendAliasListMsg.aliases = aliasInfos;
        //    SendToServer(conn, setFriendAliasListMsg, Constants.CommMessageType.SET_FRIEND_ALIAS_LIST_MSG);
        //}
        #endregion

        #region LoadPresenceInfo
        ///<summary>
        ///Load presence of friend
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        public static void LoadPresenceInfo(uint userId)
        {
            LoadPresenceMsg msg = new LoadPresenceMsg();
            msg.uid = userId;
            SendToServer(msg, Constants.Constants.CommMessageType.LOAD_PRESENCE_MSG);
        }
        #endregion

        #region getUserInfo
        ///<summary>
        ///Load presence of friend
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId">id of user</param>
        public static void GetUserInfo(uint userId)
        {
            GetUserMsg getUserMsg = new GetUserMsg();
            getUserMsg.uid = userId;

            SendToServer(getUserMsg, Constants.Constants.CommMessageType.GET_USER_MSG);
        }
        #endregion

        #region LoadOfflineMsg
        ///<summary>
        ///Load off-line Message when login
        ///</summary>
        ///<param name="conn"></param>
        ///<param name="userId"></param>
        public static void LoadOfflineMsg(uint userId)
        {
            LoadOfflineMsg loadOfflineMessage = new LoadOfflineMsg();
            loadOfflineMessage.uid = userId;

            SendToServer(loadOfflineMessage, Constants.Constants.CommMessageType.LOAD_OFFLINE_MSG);
        }
        #endregion

        //------------------------------------------------------------------------------
    }
}